import React, { useEffect, useState } from 'react';
import picture from '../../resource/picture.png';
import picture1  from '../../resource/picture1.png';
//图标
import {
    PlusCircleOutlined,
    ExclamationCircleFilled,
    SearchOutlined,
    PlusOutlined ,
    CloseCircleOutlined
} from '@ant-design/icons';
import { Input } from 'antd';
import { useNavigate,Outlet } from 'react-router-dom';
import {$getFollowList} from "../../api/starapi";
import Followlist from "../../components/followlist/followlist";
import Post1 from "../../components/post/post1";
import { $getSelfInformation} from "../../api/mineapi";
import { $getImg } from "../../api/getImgapi";
import MyNotification from "../../components/MyNotification/MyNotification";
import {$getTagList,$getPosts,$newPost,$getFollowPosts} from "../../api/layoutapi";
import {$getSearchPosts, $getSearchPostsId, $getSearchUsers, $getSearchUsersId} from "../../api/squareapi";
import {connect} from "react-redux";
import User1 from "../../components/User/user1";
import Followlist1 from "../../components/followlist/followlist1";

const { Search } = Input;
const { TextArea } = Input;

function Square({activeButton,activeButton6,search,searchstatus}){
    //显示关注按钮的状态
    const [backendData, setBackendData] = useState(0);
    //跳转页面导航
    const navigate = useNavigate();
    //控制搜索框中的输入值
    const [value2, setValue2] = useState('');
    //控制添加框中的输入值
    const [value1, setValue1] = useState('');
    //传给首页搜索框的下拉框的值
    const [options, setOptions] = useState([]);
    //传给发帖标签搜索框的下拉框的值
    const [options1, setOptions1] = useState([]);
    //控制关注和推荐的帖子的状态
    const [activeButton4, setActiveButton4] = useState('button2');
    //通知框状态
    const [notiMsg, setNotiMsg] = useState({type: "", description: ""});
    //控制单选框的值
    const [value, setValue] = useState(1);
    //传递获取的个人信息
    const [selfinformation, setSelfinformation] = useState({});
    //获取帖子的数据
    const [posts, setPosts] = useState([]);
    const [page, setPage] = useState(1);
    const [followposts,setFollowPosts]=useState([]);
    //第一行筛选按钮所处的状态
    const [activeButton1, setActiveButton1] = useState('button1');
    //第二行筛选按钮所处的状态
    const [activeButton2, setActiveButton2] = useState('button1'); // 初始状态为button1
    //第三行筛选按钮所处的状态
    const [activeButton3, setActiveButton3] = useState('button1'); // 初始状态为button1
    //为了讲useEffect中获取的图片数据在return中获得
    const [imgdata, setImgData] = useState(null);
    //更新抽屉状态
    const [open, setOpen] = useState(false);
    //获取输入框帖子的内容的实时更新
    const [post1, setPost1] = useState('');
    //获取输入框帖子的标题的实时更新
    const [post2, setPost2] = useState('');
    //添加标签后所有标签值（字符串）
    const [typeStr, setTypeStr] = useState([]);
    //添加标签后所有标签值（数字）
    const [typeInt, setTypeInt] = useState([]);
    //关注列表的数据
    const [followlists, setFollowLists] = useState([]);
    // 控制菜单打开或关闭
    const [open1, setOpen1] = useState(false);
    //选中下拉框的状态量
    const [selecttedtagid, setSelectedTagId] = useState(1999999999999999999);
    //选中下拉框的帖子标签的值
    const [selecttedtagid1, setSelectedTagId1] = useState(1999999999999999999);
    const [loading,setLoading]=useState(false);
    //控制气泡输入框的状态
    const [visible,setVisible]=useState(false);
    //搜索框中的帖子数据
    const [searchPosts,setSearchPosts]=useState([]);
    //搜索框中的用户数据
    const [searchUsers,setSearchUsers]=useState([]);
    //控制关注和推荐的点击函数
    const handleButtonClick4 = (button) => {
        setActiveButton4(button);
    };
    //获取关注列表
    const getFollowList = async () => {
        const response = await $getFollowList();
        setFollowLists(response.data);
    }
    const fetchPosts = async () => {
        try {
            let type;
            if(activeButton==='button1')
            {
                type='Enrollment';
            }
            else{
                type='Job';
            }
            const response = await $getPosts({page: page.toString(), pageSize: '10', type: type,select:'time'});
            if (response.code === 1) {
                setPosts(response.data); // 假设响应的数据结构是一个数组
            }
            else{
                setPosts([]);
            }
        } catch (error) {
            console.error('Error fetching posts:', error);
        }
    };
    useEffect(()=>{
        fetchPosts();
    },[activeButton])
    const fetchData = async () => {
        try {
            //从localstorage中获得token
            const token=localStorage.getItem('token');
            //获取个人信息
            const response = await $getSelfInformation(token);
            setSelfinformation(response.data);
            //获取个人头像
            const response3=$getImg({ studentId: response.data.studentId.toString() });
            response3.then((result) => {
                if(result.code===1){
                    const { data } = result;
                    setImgData(data);
                }
            });
        } catch (error) {
            console.error("Error fetching data:", error);
        }
    };
    //在页面滑倒最底下时调用函数加载
    const fetchMorePosts = async () => {
        if (loading) return; // 防止重复加载
        try {
            setLoading(true);
            const nextPage = page + 1;
            let type;
            if(activeButton==='button1')
            {
                type='Enrollment';
            }
            else{
                type='Job';
            }
            const response = await $getPosts({page:page.toString(),pageSize:'10',type:type});
            setPosts(prevPosts => [...prevPosts, ...response.data]);
            setPage(nextPage);
        } catch (error) {
            console.error('Error fetching more posts:', error);
        } finally {
            setLoading(false);
        }
    };
    const fetchFollowPosts=async ()=>{
        const response=await $getFollowPosts({page:'0',pageSize:'1'});
        if (response.code === 1) {
            setFollowPosts(response.data); // 假设响应的数据结构是一个数组
        }
        else{
            setFollowPosts([]);
        }
    }
    useEffect(() => {
        fetchData();//获取个人信息数据
        fetchPosts();//获取帖子数据
        fetchFollowPosts();//获取关注帖子的数据
        getFollowList();//获取关注列表
    }, []); // 确保依赖项数组为空或包含正确的依赖项项


    useEffect(()=>{
        console.log('abcdefg');
        if (!isNaN(search) && Number.isInteger(parseFloat(search))) {
            console.log("search是一个整数");
        } else {
            console.log("search不是一个整数");
        }
        console.log(search);
        console.log('abcdefg');
    },[searchstatus,search])

    //获取搜索框中的帖子数据
    const GetSearchPosts=async (search)=>{
        let type;
        if(activeButton==='button1'){
            type='Enrollment';
        }else{
            type="Job"
        }
        let response;
        if (!isNaN(search) && Number.isInteger(parseFloat(search))) {
            response= await $getSearchPostsId({page:'0',pageSize:'10',type:type,tagId:search});
        } else {
            response=await $getSearchPosts({page:'0',pageSize:'10',search:search,type:type,select:'time'});
        }
        if(response.code) {
            setSearchPosts(response.data);
        }
    }
    //获取搜索框中的帖子数据
    const GetSearchUsers=async (search)=>{
        let response;
        if (!isNaN(search) && Number.isInteger(parseFloat(search))) {
            response=await $getSearchUsersId({tagId:search,page:'1',pageSize:'10'})
        } else {
            response=await $getSearchUsers({search:search,page:'0',pageSize:'6'});
        }
        console.log(response);
        if(response.code) {
            setSearchUsers(response.data);
        }
    }
    //获取搜索框中的帖子数据和用户数据
    useEffect(()=>{
        if(activeButton6===1){
            GetSearchPosts(search);
        }
        else{
            GetSearchUsers(search);
        }
    },[activeButton6,search])

    useEffect(()=>{
        console.log('afkdjfkdjf');
        console.log(searchstatus);
        console.log('afkdjfkdjf');
    },[searchstatus])
    //在帖子滑到最底端的时候获取新的posts值
    useEffect(() => {
        const handleScroll = () => {
            // 在这里可以获取到最新的 posts 值
            if (
                window.innerHeight + document.documentElement.scrollTop ===
                document.documentElement.offsetHeight
            ) {
                fetchMorePosts();
            }
        };

        window.addEventListener('scroll', handleScroll);

        return () => {
            window.removeEventListener('scroll', handleScroll);
        };
    }, [posts]);


    //点击筛选第一行按钮事件
    const handleButtonClick1 = (buttonId) => {
        setActiveButton1(buttonId);
    };
    //点击筛选第二行按钮事件
    const handleButtonClick2 = (buttonId) => {
        setActiveButton2(buttonId);
    };
    //点击筛选第三行按钮事件
    const handleButtonClick3 = (buttonId) => {
        setActiveButton3(buttonId);
    };
    //选择框的点击事件
    const onChange = (e) => {
        console.log('radio checked', e.target.value);
        setValue(e.target.value);
    };
    //生成新的帖子
    const handlePublish = async() => {
        let tag;
        if(activeButton==='button1')
        {
            tag=1;
        }
        else
        {
            tag=2;
        }

        const response = await $newPost({content:post1,title:post2,tag:tag,tags:typeInt});
        // if (response.code) {
        //     setNotiMsg({ type: "success", description: response.message});
        // } else {
        //     setNotiMsg({ type: "error", description: response.message })
        // }
        // setPost1('');
        //这里写提交帖子的函数
    };
    //点击标签删除按钮
    const handleRemoveTag = (tagIndex) => {
        const updatedTags = typeStr.filter((_, index) => index !== tagIndex);
        const updatedTags1 = typeInt.filter((_, index) => index !== tagIndex);
        setTypeStr(updatedTags);
        setTypeInt(updatedTags1);
    };
    //点击自身头像
    const handleAvatarClick=()=>{
        setOpen1(!open1);
    }
    //搜索框下的下拉选择框
    const onSelect1 = (value, option) => {
        // 更新输入框中的值为选中的 tagName
        setValue2(option.label);
        // 保存选中的 tagId 到状态量
        setSelectedTagId(value);
    };
    //搜索框的回调函数
    const onChange1 = async (value2) => {
        setValue2(value2);
        let response;
        if(value===1) {
            response = await $getTagList({search: value2, page: '0', pageSize: '7'});
        }
        else{
            response = await $getUserTagList({search: value2, page: '0', pageSize: '7'});
        }
        if(response.data) {
            const transformedOptions = response.data.map(item => ({value: item.tagId, label: item.tagName}));
            // 更新下拉框的选项
            setOptions(transformedOptions);
        }
    };
    //搜索框点击搜索按钮
    const onSearch1=(value2)=>{
        //这里要写搜索的部分
    }
    //添加标签框下的下拉选择框
    const onSelect2 = (value, option) => {
        // 更新输入框中的值为选中的 tagName
        setValue1(option.label);
        setSelectedTagId1(value);
        // 保存选中的 tagId 到状态量
    };
    //添加标签框的回调函数
    const onChange2 = async (value1) => {
        setValue1(value1);
        const response = await $getTagList({search:value1,page:'0',pageSize:'7'});
        if(response.data) {
            const transformedOptions = response.data.map(item => ({value: item.tagId, label: item.tagName}));
            // 更新下拉框的选项
            setOptions1(transformedOptions);
        }
    };
    //添加标签框点击添加按钮
    const onSearch2=()=>{
        setTypeInt([...typeInt,selecttedtagid1]);
        setTypeStr([...typeStr,value1]);
        setValue1('');
    }
    //监视关注列表的变化
    useEffect(()=>{
        getFollowList();//获取关注列表
    },[backendData]);
    return(
        <>
            <div className='ContentLeft' style={{flex: '1'}}>
            <div style={{
                backgroundColor: 'white',
                width: '60vw',
                minHeight: '100vh',
                marginLeft: '170px',
                marginTop: '25px'
            }}>{!searchstatus?(
                <div className='LeftHeader' style={{borderBottom: '4px solid rgb(88, 209, 200)'}}>
                    <div style={{display: 'flex', marginLeft: '80px'}}>
                        <div
                            onClick={() => handleButtonClick4('button1')}
                            style={activeButton4 === 'button1' ? {
                                    fontWeight: 'bold',
                                    fontSize: '28px',
                                    backgroundColor: 'rgb(88, 209, 200)', marginRight: '20px',
                                    borderTopLeftRadius: '5px',
                                    borderTopRightRadius: '5px',
                                    paddingTop: '21px'
                                } :
                                {
                                    fontWeight: 'bold',
                                    fontSize: '28px',
                                    marginRight: '20px',
                                    paddingTop: '21px'
                                }
                            }
                        >
                            关注
                        </div>
                        <div
                            onClick={() => handleButtonClick4('button2')}
                            style={activeButton4 === 'button2' ? {
                                    color: "rgb(0,0,0,0.5)",
                                    fontSize: '28px',
                                    backgroundColor: 'rgb(88, 209, 200)', borderTopLeftRadius: '5px',
                                    borderTopRightRadius: '5px',
                                    paddingTop: '21px'
                                } :
                                {
                                    color: "rgb(0,0,0,0.5)",
                                    fontSize: '28px',
                                    paddingTop: '21px',
                                }
                            }
                        >
                            推荐
                        </div>
                    </div>
                </div>): (<div className='LeftHeader' style={{borderBottom: '4px solid rgb(88, 209, 200)'}}>
                <div style={{display: 'flex', marginLeft: '80px'}}>
                    <div
                        style={
                            {
                                fontWeight: 'bold',
                                fontSize: '28px',
                                marginRight: '20px',
                                paddingTop: '21px'
                            }
                        }
                    >
                    </div>
                    <div
                        style={
                            {
                                color: "rgb(0,0,0,0.5)",
                                fontSize: '28px',
                                paddingTop: '21px',
                            }
                        }
                    >
                    </div>
                </div>
            </div>)}
                <div>
                    {!searchstatus ? (
                        // 如果 searchstatus 为 true，则执行此部分代码
                        activeButton4 === 'button2' ? (
                            posts.map((post, index) => (
                                <Post1 key={index} post={post} avater={imgdata}/>
                            ))
                        ) : (
                            followposts.map((post, index) => (
                                <Post1 key={index} post={post} avater={imgdata}/>
                            ))
                        )
                    ) : (
                        activeButton6 === 1 ? (
                            searchPosts.map((post, index) => (
                                <Post1 key={index} post={post} avater={imgdata}/>
                            ))
                        ) : (
                            searchUsers.map((user, index) => (
                                <User1 key={index} user={user}/>
                            ))
                        )
                    )}
                </div>


            </div>
            </div>
            <div className='ContentRight' style={{flex: '1', width: '540px', minHeight: '100vh'}}>
                <div className='RightTop'>
                    <div style={{
                        backgroundColor: 'white',
                        width: '350px',
                        height: '500px',
                        marginTop: '25px',
                        marginLeft: '10px',
                        display: 'flex'

                    }}>
                        <div style={{}}>
                            <div style={{
                                marginBottom: '20px',
                                marginTop: '20px',
                                marginLeft: '20px',
                                display: 'flex',
                                alignItems: 'center'
                            }}>
                                <img src={picture} style={{width: '20px', height: '20px'}}/>
                                <div style={{fontWeight: 'bold', marginLeft: '2px'}}>关注用户</div>
                            </div>
                            {followlists.map((item, index) => (
                                <Followlist key={index} item={item}
                                           />
                            ))}
                        </div>
            </div>
            <div style={{
                backgroundColor: 'white',
                width: '350px',
                height: '450px',
                marginTop: '10px',
                marginLeft: '10px'
            }}>
                <div style={{marginLeft:'3px',paddingTop:'10px'}}>
                    <div style={{marginTop:'20px',display:'flex',marginLeft:'20px',alignItems:'center',marginBottom:'20px'}}>
                        <img src={picture1} width='25px' height='25px'/>
                        <div style={{fontWeight:'bold'}}>推荐关注用户</div>
                    </div>
                    <div>
                        {followlists.map((item, index) => (
                            <Followlist1 key={index} item={item}
                            />
                        ))}
                    </div>
                </div>
            </div>
        </div>
        <div className='RightLeft'></div>
    </div>
        </>
    )
}
const mapStateToProps = (state) => {
    return {
        activeButton: state.reducer1Data.activeButton,
        activeButton6: state.reducer2Data.activeButton6,
        search: state.reducer3Data.search,
        searchstatus: state.reducer4Data.searchstatus,
    };
};
const SquareContainer = connect(mapStateToProps)(Square);
export default SquareContainer;